﻿using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using NPOI.SS.Formula.Functions;
using System.Security.Policy;
using System;
using TyMES.Communication;
using TyMES.PassStationCommunication;
using WalkingTec.Mvvm.Core;
using System.Threading.Tasks;
using TyMES.Model.GetData;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using System.ComponentModel.DataAnnotations;

namespace TyMES.Services
{
    public class BadCodeService
    {
        private readonly ILogger logger;
        private readonly IConfiguration configuration;
        private readonly HttpService httpService;
        private readonly IServiceScope serviceScope;
        private readonly WTMContext context;
        private readonly string factoryCode;
        private readonly string mesIP;
        private readonly string mesPort;


        public BadCodeService(ILogger<BadCodeService> logger, IConfiguration configuration, HttpService httpService, IServiceScopeFactory serviceScopeFactory)
        {
            this.logger = logger;
            this.configuration = configuration;
            this.httpService = httpService;
            this.serviceScope = serviceScopeFactory.CreateScope();
            var sp = this.serviceScope.ServiceProvider;
            this.context = sp.GetRequiredService<WTMContext>();
            this.factoryCode = configuration["FactoryCode"];
            this.mesIP = configuration["MESIP"];
            this.mesPort = configuration["MESPORT"];
        }

        private async Task<BadCodetResponse> SyncTemplateAsync(BadCodeRequest request)
        {
            try
            {
                string url = "http://" + mesIP + ":" + mesPort + configuration["ROUTEBOM"];
                string postData = JsonConvert.SerializeObject(request);
                //记录请求报文
                logger.LogInformation(postData);
                string value = await httpService.PostDataAsync(url, postData);
                //记录响应报文
                logger.LogInformation(value);
                BadCodetResponse response = JsonConvert.DeserializeObject<BadCodetResponse>(value);
                return response;
            }
            catch (Exception)
            {
                throw;
            }
        }


        private void Update(BadCodetResponseSup badCode)
        {
            var res = this.context.DC.Set<BadCodeTemplate>().SingleOrDefault(e => e.OperationCode == badCode.operationCode
                       && e.BadCode == badCode.badCode);
            if(res != null)
            {
                res.AddTime = badCode.addTime;
                res.BadCode = badCode.badCode;
                res.BadName = badCode.badName;
                res.BadTypeCode = badCode.badTypeCode;
                res.BadTypeName = badCode.badTypeName;
                res.DataStatus = badCode.dataSatus;
                res.EditTime = badCode.editTime;
                res.EnableStatus = badCode.enableStatus;
                res.FactoryCode = badCode.factoryCode;
                res.Field1 = badCode.field1;
                res.Field2 = badCode.field2;
                res.Field3 = badCode.field3;
                res.Field4 = badCode.field4;
                res.Field5 = badCode.field5;
                res.OperationCode = badCode.operationCode;
            } 
            else
            {
                var item = new BadCodeTemplate()
                {
                    AddTime = badCode.addTime,
                    BadCode = badCode.badCode,
                    BadName = badCode.badName,
                    BadTypeCode = badCode.badTypeCode,
                    BadTypeName = badCode.badTypeName,
                    DataStatus =badCode.dataSatus,
                    EditTime = badCode.editTime,
                    EnableStatus = badCode.enableStatus,
                    FactoryCode = badCode.factoryCode,
                    Field1 = badCode.field1,
                    Field2 = badCode.field2,
                    Field3 = badCode.field3,
                    Field4 = badCode.field4,
                    Field5 = badCode.field5,
                    OperationCode = badCode.operationCode
                };
                this.context.DC.Set<BadCodeTemplate>().Add(item);
            }
        }

        public async Task<ResponseBase> UpdateBadCodeTemplate(OperationPara para)
        {
            BadCodeRequest request = new BadCodeRequest()
            {
                serviceId = "Base008_BadCode",
                factoryCode = this.factoryCode,
                operationCode = para.OperationCode
            };
            try
            {
                BadCodetResponse res = await SyncTemplateAsync(request);
                if(res.code == "000000")
                {
                    //修改保存本地信息
                    foreach (var item in res.data)
                    {
                        Update(item);
                    }
                }
                else
                {
                    return new ResponseBase(false, res.mesg);
                }
                await this.context.DC.SaveChangesAsync();
                return new ResponseBase(true, "同步成功");
            }
            catch (Exception ex)
            {
                return new ResponseBase(false, ex.Message);
            }
        }
        

    }
}
